package main

import (
	"fmt"
	"hello-web-session/session"
	"html/template"
	"log"
	"net/http"
	"strings"
)

var globalSession *session.Manager

func init() {
	globalSession, _ = session.NewManager("memory", "gosessionid", 3600)
	go globalSession.GC()
}

func sayHelloName(w http.ResponseWriter, r *http.Request) {
	r.ParseForm() // 解析url传递的参数，对于POST则解析响应包的主体request body
	// 如果没有ParseForm()下面无法获取表单数据
	fmt.Println(r.Form) // 输出到服务器端的打印信息
	fmt.Println("path", r.URL.Path)
	fmt.Println("scheme", r.URL.Scheme)
	fmt.Println(r.Form["url_long"])
	for k, v := range r.Form {
		fmt.Println("key:", k)
		fmt.Println("val:", strings.Join(v, ""))
	}
	fmt.Fprintf(w, "Hello dralee!")
}

func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method) // 请求的方法
	r.ParseForm()                    // 调用r.Form[] 需要手动调用r.ParseForm
	session := globalSession.SessionStart(w, r)
	if r.Method == "GET" {
		t, _ := template.ParseFiles("gtpls/login.gtpl")
		//w.Header().Set("Content-Type", "text/html")
		log.Println(t.Execute(w, session.Get("username"))) // t.Execute(w, 参数），无参传入nil
	} else {
		session.Set("username", r.Form["username"])
		http.Redirect(w, r, "/", 302)
	}
}

// 劫持过程
// 防止劫持方式,先设置cookie为httponly
// 1、在每次请求生成一个token，请求提交时较难该token
// 2、间隔生成新的SID
func count(w http.ResponseWriter, r *http.Request) {
	session := globalSession.SessionStart(w, r)
	countnumKey := "countnum"
	ct := session.Get(countnumKey)
	if ct == nil {
		session.Set(countnumKey, 1)
	} else {
		session.Set(countnumKey, (ct.(int) + 1))
	}
	t, _ := template.ParseFiles("gtpls/count.gtpl")
	w.Header().Set("Content-Type", "text/html")
	t.Execute(w, session.Get(countnumKey))
}

func main() {
	http.HandleFunc("/", sayHelloName)       // 设置访问路由
	http.HandleFunc("/login", login)         // 设置访问路由
	http.HandleFunc("/count", count)         // 设置访问路由
	err := http.ListenAndServe(":9090", nil) // 设置监听端口
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
